package com.newly.common.core.utils.file;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.ftp.Ftp;
import com.newly.common.base.exception.FileClientException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;

/**
 * @program: file-client
 * @remark: ftp文件客户端
 * @author: guan
 * @create: 2021-11-05 14:36
 */
public class FTPClient extends AbstractFileClient implements IFileClient {

    @Override
    public String upload(String fileName, String srcPath, String relativePath) {
        return this.upload(fileName, this.getFileStream(srcPath), relativePath);
    }

    @Override
    public String upload(String fileName, InputStream fileStream, String relativePath) {
        if (ObjectUtil.isEmpty(fileStream)) {
            throw new FileClientException("文件流不能为空");
        }

        // 根据规则得到文件名
        fileName = this.handleFileName(fileName);

        // 文件路劲
        relativePath = handleFilePath(ftpRootPath, relativePath);

        // 上传至ftp
        Ftp ftp = null;
        try {
            ftp = this.getFtpInstance();
            ftp.upload(relativePath, fileName, fileStream);
        } catch (Exception e) {
            throw FileClientException.getInstance("文件上传失败： " + e);
        } finally {
            closeFd(ftp, fileStream);
        }

        return this.realResPath(relativePath, fileName);
    }

    @Override
    public String upload(String fileName, MultipartFile multipartFile, String relativePath) {
        return this.upload(fileName, this.getFileStream(multipartFile), relativePath);
    }

    @Override
    public String download(String fileName, String relativePath) {
        Ftp ftp = this.getFtpInstance();
        File file = new File("C:\\Users\\NEWLT-CCS\\Desktop\\tmp", fileName);
        ftp.download(relativePath, fileName, file);
        return null;
    }

    @Override
    public String download(String fileName) {
        return this.download(fileName, null);
    }


    /**
     * @return ftp实例对象
     */
    private Ftp getFtpInstance() {
        return new Ftp(ftpId, ftpPort, ftpUsername, ftpPassword);
    }
}
